<template>
	<view class="uni-flex uni-column">

		<view class="uni-flex uni-column" style="-webkit-justify-content: center;justify-content: center;margin-right: 12upx; height: 350upx; text-align: center;">
			<view @click="imgClick">
				<image mode="aspectFit" style="width: 234upx;height: 234upx;" src="/static/img/bluetooth/bluetooth.png" />
			</view>
		</view>
		<view v-if="bluetoothArr && bluetoothArr.length > 0">
			<uni-list>
				<!-- 水平排列，右图左文 -->
				<uni-list-item :title="item.name" v-for="(item,index) in bluetoothArr" :key="index">
					<template v-slot:footer>
						<view class="uni-thumb" style="margin: 0; margin-right: 10upx;" @click="rowClick(item)">
							<image v-if="deviceId === item.deviceId" src="/static/img/bluetooth/Connected.png" mode="aspectFit" style="width: 44upx;height: 44upx;"></image>
							<image v-else src="/static/img/bluetooth/notConnected.png" mode="aspectFit" style="width: 44upx;height: 44upx;"></image>

						</view>
					</template>
				</uni-list-item>


			</uni-list>

		</view>
		<view v-else style="text-align: center;">
			Bluetooth is on, searching for nearby devices...
		</view>
	</view>
</template>

<script>
	export default {
		components: {},
		data() {
			return {
				bluetoothArr: [],
				hideDo: 0,
				deviceId: 0,

				dataInfo: {

				},
			}
		},
		onHide() {
			// console.log('App onHide');
			this.hideDo = 1;
			this.stopBluetoothDevicesDiscovery();
		},
		onShow() {
			// console.log('App onShow');

			if (this.hideDo === 1) {
				this.hideDo = 2;
				this.startBluetoothDevicesDiscovery()
			}
		},
		onLoad() {
			// let buf = this.str2ab("$DATA0:1243,54,12");
			// let str = this.ab2str(buf)
			// console.log(str)
			// console.log('App onLoad');
			// 在页面加载时候初始化蓝牙适配器
			uni.openBluetoothAdapter({
				success: (e) => {
					// 初始化完毕
					if (e.errMsg == "openBluetoothAdapter:ok") {
						uni.getConnectedBluetoothDevices({
							services: [],
							success: (res) => {
								if (res.devices.length) {
									console.log("初始化完毕", JSON.stringify(res.devices))
								} else {
									this.startBluetoothDevicesDiscovery()
								}
							}
						})

					}
				},
				fail: (e) => {
					if (e.errCode == 10001) {
						uni.showModal({
							title: 'Tips',
							content: '请打开蓝牙设备',
							showCancel: false,
							success: (res) => {
								uni.removeStorageSync("left")
								if (res.confirm) {
									uni.navigateBack({
										delta: 1
									})
								}
							}
						});
					}
				}
			});
			uni.onBLEConnectionStateChange((res) => {
				// 该方法回调中可以用于处理连接意外断开等异常情况
				console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)

				if (!res.connected) {
					uni.closeBLEConnection({
						deviceId: res.deviceId,
						success: res => {
							console.log(res);
						}
					})
					this.deviceId = 0;
					uni.$emit('closeClick', res.deviceId)
				}
			})
		},
		computed: {
			i18n() {
				return this.$t('index')
			}
		},
		methods: {
			imgClick() {


			},
			rowClick(item) {

				if (this.deviceId === item.deviceId) {
					this.closeBLEConnection(item.deviceId)

				} else {
					this.createBLEConnection(item.deviceId)
				}
			},
			startBluetoothDevicesDiscovery() {
				//在页面显示的时候判断是都已经初始化完成蓝牙适配器若成功，则开始查找设备
				uni.startBluetoothDevicesDiscovery({
					services: ["FFE0"],
					success: res => {
						if (res.errMsg == "startBluetoothDevicesDiscovery:ok") {
							this.onBluetoothDeviceFound();
						}

					},
					fail: res => {
						uni.showToast({
							icon: "none",
							title: "查找设备失败！",
							duration: 3000
						})
					}
				});
			},
			/**
			 * 停止搜索蓝牙设备
			 */
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log('停止搜索蓝牙设备:' + e.errMsg);
					},
					fail: e => {
						console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);
					}
				});
			},
			/**
			 * 发现外围设备
			 */
			onBluetoothDeviceFound() {
				uni.onBluetoothDeviceFound(devices => {
					this.getBluetoothDevices();
				});
			},
			/**
			 * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
			 */
			getBluetoothDevices() {
				uni.getBluetoothDevices({
					success: (res) => {
						let bluetooth = [];

						// console.log("查找到的设备", JSON.stringify(res.devices))
						let deviceIdOk = false;
						res.devices.forEach(item => {
							// if (item.name && item.name.toLowerCase().includes("smartfoot")) {
							// 	this.bluetooth.push(item);
							// }

							if (item.name) {
								bluetooth.push(item);
								if (item.deviceId === this.deviceId) {
									deviceIdOk = true;
								}
							}
						});
						if (!deviceIdOk && this.bluetoothArr.length) {
							for (let obj of this.bluetoothArr) {
								if (obj.deviceId === this.deviceId) {
									bluetooth.push(obj);
									break;
								}
							}
						}
						this.bluetoothArr = bluetooth;
						console.log("设备数量", bluetooth.length)
						//尝试连接过历史连接的蓝牙设备
						bluetooth.forEach((item, index) => {
							if (item.deviceId == uni.getStorageSync('oldleft')) {
								this.createBLEConnection(item.deviceId);
								if (!uni.getStorageSync("left")) {
									uni.setStorageSync("left", uni.getStorageSync('oldleft'))
								}
							}
						})
					}
				});
			},
			//断开蓝牙连接
			closeBLEConnection(deviceId) {
				uni.closeBLEConnection({
					deviceId: deviceId,
					success: res => {
						this.deviceId = 0;
						if (uni.getStorageSync('left') == deviceId) {
							uni.removeStorageSync("left")
							uni.removeStorageSync("oldleft")
						}
					}
				})
			},
			// 连接蓝牙设备
			createBLEConnection(deviceId, successCallBack) {
				this.deviceId = deviceId;

				uni.createBLEConnection({
					deviceId: this.deviceId,
					success: res => {
						uni.showLoading({
							title: 'Loading...',
							mask: true
						});
						setTimeout(function() {
							uni.hideLoading();
						}, 3000);
						this.dataInfo = {
							dataBuff: '',
							$INFO: [],
							$DATA0: [],
							$DATA1: [],
							$DATA2: [],
							$DATA3: [],
							$TOTAL: [],
							sendTime: false
						}
						this.getBLEDeviceServices(this.deviceId);
						uni.setBLEMTU({
							deviceId: this.deviceId,
							mtu: 20000,
							success: e => {
								console.log("uni.setBLEMTU success")
							},
							fail: e => {
								console.log("uni.setBLEMTU fail")
							}
						})

						if (successCallBack) {
							successCallBack();
						}
					},
					fail: res => {
						console.error("连接蓝牙设备 失败")
					}
				})
			},
			//获取蓝牙设备所有服务(service)。
			getBLEDeviceServices(deviceId) {
				setTimeout(() => {
					uni.getBLEDeviceServices({
						deviceId: deviceId,
						success: (res) => {
							this.serverList = res.services
							res.services.forEach((item) => {
								if (item.uuid.indexOf("FFE0") != -1) {
									this.serviceId = item.uuid;
									this.getBLEDeviceCharacteristics(this.deviceId)
								}
							})
						}
					})
				}, 1000)
			},

			// 获取蓝牙特征值
			getBLEDeviceCharacteristics(deviceId) {
				setTimeout(() => {
					uni.getBLEDeviceCharacteristics({
						deviceId: deviceId,
						serviceId: this.serviceId,
						success: (res) => {
							console.log("获取蓝牙特征值", JSON.stringify(res))
							this.characteristics = res.characteristics
							res.characteristics.forEach((item) => {
								if (item.uuid.indexOf("FFE1") != -1) {
									this.characteristicId = item.uuid;
									console.log('characteristicId:', this.characteristicId)
									this.notifyBLECharacteristicValueChange(this.deviceId)
								}
							})
						},
						fail: (res) => {
							console.log(res)
						}
					})
				}, 1000)
			},
			// 启用 notify 功能
			notifyBLECharacteristicValueChange(deviceId) {
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					deviceId: deviceId,
					serviceId: this.serviceId,
					characteristicId: this.characteristicId,
					success: (res) => {
						console.log('notifyBLECharacteristicValueChange success', res.errMsg)

						this.onBLECharacteristicValueChange(this.deviceId);
					},
					fail: (res) => {
						console.log('notifyBLECharacteristicValueChange success', res.errMsg)
					}
				})
			},
			// 监听低功耗蓝牙设备的特征值变化
			onBLECharacteristicValueChange(deviceId) {
				uni.onBLECharacteristicValueChange((res) => {
					// console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)

					// console.log('监听低功耗蓝牙设备的特征值变化:' + this.ab2str(res.value), res.value.byteLength)
					this.analysisData(this.ab2str(res.value), res.deviceId)
				})
			},
			ab2str(buf) {
				return String.fromCharCode.apply(null, new Uint8Array(buf));
			},
			// 读取设备二进制数据
			readBLECharacteristicValue() {
				uni.readBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.characteristicId,
					success: (res) => {
						console.log('readBLECharacteristicValue:', res)
						this.readCode = res.errCode;
						this.readCodeMsg = res.errMsg;
						this.onBLECharacteristicValueChange(this.deviceId);
					},
					fail: (res) => {
						console.log('readBLECharacteristicValue:', res)
						this.readCode = res.errCode;
						this.readCodeMsg = res.errMsg;
						this.onBLECharacteristicValueChange(this.deviceId);
					}
				})
			},
			str2ab(str) {
				let buf = new ArrayBuffer(str.length); // 每个字符占用2个字节
				let bufView = new Uint8Array(buf);
				for (let i = 0; i < str.length; i++) {
					bufView[i] = str.charCodeAt(i);
				}
				return buf;
			},
			// 发送数据
			writeBLECharacteristicValue(str) {
				let buffer = this.str2ab(str)
				console.log("发送数据:" + str, buffer.byteLength, this.characteristicId)
				uni.writeBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.characteristicId,
					value: buffer,
					success: (res) => {
						this.returnMessage = res.errMsg;
						console.log('writeBLECharacteristicValue success', res.errMsg)
					},
					fail: (res) => {
						this.returnMessage = res.errMsg;
						console.log('writeBLECharacteristicValue fail', res.errMsg)
					}
				})
			},
			sendTimeDo() {
				if (!this.dataInfo.sendTime) {
					debugger
					let tmpStr = "$TIME:," + this.$utils.formatDate(new Date(), "YYYY,MM,DD,HH,mm,ss") + ";";
					setTimeout(() => {
						this.writeBLECharacteristicValue(tmpStr)
					}, 1000)
					// this.writeBLECharacteristicValue(tmpStr.substring(0,10))
					// setTimeout(()=>{
					// 	this.writeBLECharacteristicValue(tmpStr.substring(10))
					// },1000)
					this.dataInfo.sendTime = true;
				}
			},
			analysisData(data, deviceId) {
				if (!data) {
					return
				}
				console.log(data + "                                   #")
				let dataBuff = this.dataInfo.dataBuff + data
				if (!dataBuff.startsWith("$")) {
					let arr = dataBuff.split("$");
					if (arr && arr.length > 1) {
						dataBuff = "$" + arr[1]
					}
				}
				let pos = dataBuff.indexOf(";")
				if (pos === -1) {
					this.dataInfo.dataBuff = dataBuff
					return;
				}
				this.dataInfo.dataBuff = dataBuff.substring(pos)
				let value = dataBuff.substring(0, pos)
				console.log("接收数据:" + value + "                     ")
				let tmpArr = value.split(":")
				if (tmpArr.length === 2) {
					let dataArr = tmpArr[1].split(",")
					this.dataInfo[tmpArr[0]] = dataArr
				}
				let isOk = true;
				if (this.dataInfo.$INFO.length !== 5) {
					isOk = false;
				}
				if (this.dataInfo.$DATA0.length !== 11) {
					isOk = false;
				}
				if (this.dataInfo.$DATA1.length !== 11) {
					isOk = false;
				}
				if (this.dataInfo.$DATA2.length !== 11) {
					isOk = false;
				}
				if (this.dataInfo.$DATA3.length !== 11) {
					isOk = false;
				}
				if (this.dataInfo.$TOTAL.length !== 7) {
					isOk = false;
				}
				if (isOk) {
					uni.setStorageSync("bluetooth.dataInfo", this.dataInfo)
					this.sendTimeDo()
				}
			}
		}
	}
</script>

<style>

</style>
